package handlers

import (
	"algs/cache"
	"algs/models"
	"algs/pkg"
	"encoding/json"
	"github.com/gin-gonic/gin"
	"net/http"
	"time"
)

func Login(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")
	if username == "" || password == "" {
		c.JSON(http.StatusOK, gin.H{
			"code": 500,
			"msg":  "用户名或者密码为空",
		})
		return
	}

	redis_login_key := "login_error_" + username
	errCount, _ := cache.Rdb.Get(cache.Ctx, redis_login_key).Int()
	if errCount >= 3 {
		c.JSON(http.StatusOK, gin.H{
			"code": 500,
			"msg":  "密码错误三次,禁止登录",
		})
		return
	}

	var user models.User
	models.DB.Where("username=?", username).First(&user)
	if user.ID == 0 {
		c.JSON(http.StatusOK, gin.H{
			"code": 500,
			"msg":  "用户不存在",
		})
		return
	}

	if user.Password != pkg.Mk5str(password) {

		cache.Rdb.Incr(cache.Ctx, redis_login_key) //密码错误一次，缓存中的错误次数+1
		if errCount == 2 {
			cache.Rdb.Set(cache.Ctx, redis_login_key, 3, time.Hour*2)
			c.JSON(http.StatusOK, gin.H{
				"code": 500,
				"msg":  "密码错误3次,封禁2个小时",
			})
			return
		}
		c.JSON(http.StatusOK, gin.H{
			"code": 500,
			"msg":  "密码错误",
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "success",
	})
	return
}
func List(c *gin.Context) {
	var alge []models.Alge
	redis_alge := "alge_list"
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_alge).Result()
	if cacheData == "" {
		models.DB.Find(&alge)
		jsonData, _ := json.Marshal(alge)
		cache.Rdb.Set(cache.Ctx, redis_alge, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &alge)
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "展示成功",
		"data": alge,
	})
	return
}

func Detail(c *gin.Context) {
	id := c.Query("id")
	var alge models.Alge
	models.DB.Where("id=?", id).First(&alge)
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": alge,
	})
}
